const { Account, Category } = require('../models');
const { Op } = require('sequelize');

// 获取账号列表
exports.getAccounts = async (req, res) => {
  try {
    const { categoryId, search } = req.query;
    const userId = req.user.userId;
    
    // 构建查询条件
    const where = { userId };
    
    if (categoryId && categoryId !== '1') { // 1 通常是'全部'分类
      where.categoryId = categoryId;
    }
    
    // 查询账号列表
    const accounts = await Account.findAll({
      where,
      include: [{
        model: Category,
        attributes: ['id', 'name']
      }],
      order: [['updatedAt', 'DESC']]
    });
    
    // 搜索过滤（如果提供了搜索词）
    let filteredAccounts = accounts;
    if (search) {
      const searchLower = search.toLowerCase();
      filteredAccounts = accounts.filter(account => 
        account.name.toLowerCase().includes(searchLower) ||
        account.username.toLowerCase().includes(searchLower) ||
        (account.url && account.url.toLowerCase().includes(searchLower)) ||
        (account.note && account.note.toLowerCase().includes(searchLower))
      );
    }
    
    res.status(200).json({
      success: true,
      data: filteredAccounts
    });
  } catch (error) {
    console.error('获取账号列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取账号列表失败，请稍后重试'
    });
  }
};

// 获取单个账号详情
exports.getAccountDetail = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;
    
    const account = await Account.findOne({
      where: { id, userId },
      include: [{
        model: Category,
        attributes: ['id', 'name']
      }]
    });
    
    if (!account) {
      return res.status(404).json({
        success: false,
        message: '账号不存在'
      });
    }
    
    res.status(200).json({
      success: true,
      data: account
    });
  } catch (error) {
    console.error('获取账号详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取账号详情失败，请稍后重试'
    });
  }
};

// 创建账号
exports.createAccount = async (req, res) => {
  try {
    const {
      name,
      url,
      username,
      password,
      categoryId,
      note
    } = req.body;
    
    // 验证输入
    if (!name || !username || !password || !categoryId) {
      return res.status(400).json({
        success: false,
        message: '请填写必填字段'
      });
    }
    
    // 创建账号
    const account = await Account.create({
      userId: req.user.userId,
      name,
      url,
      username,
      password, // 注意：这里的密码应该已经在前端加密过
      categoryId,
      note
    });
    
    // 获取完整的账号信息
    const createdAccount = await Account.findByPk(account.id, {
      include: [{
        model: Category,
        attributes: ['id', 'name']
      }]
    });
    
    res.status(201).json({
      success: true,
      message: '账号创建成功',
      data: createdAccount
    });
  } catch (error) {
    console.error('创建账号失败:', error);
    res.status(500).json({
      success: false,
      message: '创建账号失败，请稍后重试'
    });
  }
};

// 更新账号
exports.updateAccount = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      name,
      url,
      username,
      password,
      categoryId,
      note
    } = req.body;
    
    // 验证输入
    if (!name || !username || !password || !categoryId) {
      return res.status(400).json({
        success: false,
        message: '请填写必填字段'
      });
    }
    
    // 查找账号
    const account = await Account.findOne({
      where: { id, userId: req.user.userId }
    });
    
    if (!account) {
      return res.status(404).json({
        success: false,
        message: '账号不存在'
      });
    }
    
    // 更新账号
    await account.update({
      name,
      url,
      username,
      password, // 注意：这里的密码应该已经在前端加密过
      categoryId,
      note
    });
    
    // 获取更新后的账号信息
    const updatedAccount = await Account.findByPk(id, {
      include: [{
        model: Category,
        attributes: ['id', 'name']
      }]
    });
    
    res.status(200).json({
      success: true,
      message: '账号更新成功',
      data: updatedAccount
    });
  } catch (error) {
    console.error('更新账号失败:', error);
    res.status(500).json({
      success: false,
      message: '更新账号失败，请稍后重试'
    });
  }
};

// 删除账号
exports.deleteAccount = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;
    
    // 查找账号
    const account = await Account.findOne({
      where: { id, userId }
    });
    
    if (!account) {
      return res.status(404).json({
        success: false,
        message: '账号不存在'
      });
    }
    
    // 删除账号
    await account.destroy();
    
    res.status(200).json({
      success: true,
      message: '账号删除成功'
    });
  } catch (error) {
    console.error('删除账号失败:', error);
    res.status(500).json({
      success: false,
      message: '删除账号失败，请稍后重试'
    });
  }
};

// 批量获取账号（用于同步）
exports.syncAccounts = async (req, res) => {
  try {
    const { lastSyncTime } = req.query;
    const userId = req.user.userId;
    
    const where = { userId };
    
    // 如果提供了最后同步时间，只返回更新的数据
    if (lastSyncTime) {
      where.updatedAt = { [Op.gt]: new Date(lastSyncTime) };
    }
    
    const accounts = await Account.findAll({
      where,
      include: [{
        model: Category,
        attributes: ['id', 'name']
      }]
    });
    
    res.status(200).json({
      success: true,
      data: {
        accounts,
        syncTime: new Date().toISOString()
      }
    });
  } catch (error) {
    console.error('同步账号失败:', error);
    res.status(500).json({
      success: false,
      message: '同步账号失败，请稍后重试'
    });
  }
};